//
//  Store.swift
//  TodoItemDemo
//
//  Created by alex on 2017/7/31.
//  Copyright © 2017年 RoseVision. All rights reserved.
//

import UIKit

protocol ActionType {}
protocol StateType {}
protocol CommandType {}



class Store<A: ActionType, S: StateType, C: CommandType> {
    let reducer: (_ action: A, _ state: S) -> (S, C?)
    var subscriber: ((_ state: S, _ previousState: S, _ command: C?) -> Void)?
    var state: S
    
    init(reducer: @escaping (A, S) -> (S, C?), initialState: S) {
        self.reducer = reducer
        self.state = initialState
    }
    
    func subscribe(_ handle: @escaping (S, S, C?) -> Void) {
        self.subscriber = handle
    }
    
    func unSubSribe() {
        self.subscriber = nil
    }
    
    func dispatch(action:A) {
        let previousState = state
        let (nextState, command) = reducer(action, previousState)
        state = nextState
        subscriber?(state, previousState, command)
    }
    
}
